# coding: utf-8
# flask + gevent + multiprocess + wsgi

from gevent import monkey
from gevent.pywsgi import WSGIServer  # 关键

monkey.patch_all()  # 猴子补丁如果遇见耗时操作会自动进行协程的切换

# 如果涉及 gRPC 引入兼容处理方式
# import grpc.experimental.gevent as grpc_gevent  # gevent和grpc扩展
# grpc_gevent.init_gevent() # 解决 gevent/gRPC 兼容


import datetime
import os
from multiprocessing import cpu_count, Process
from flask import Flask, jsonify

app = Flask(__name__)


@app.route("/halo", methods=['GET'])
def function_benchmark():
    return jsonify(
        {
            "status": "ok",
            "time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
            "pid": os.getpid()
        }
    ), 200


def run(MULTI_PROCESS):
    if MULTI_PROCESS == False:
        WSGIServer(('0.0.0.0', 8080), app).serve_forever()
    else:
        mulserver = WSGIServer(('0.0.0.0', 8080), app)
        mulserver.start()

        def server_forever():
            mulserver.start_accepting()
            mulserver._stop_event.wait()

        for i in range(cpu_count()):
            p = Process(target=server_forever)
            p.start()


if __name__ == "__main__":
    # 单进程 + 协程
    run(False)
    # 多进程 + 协程
    # run(True)